/**
 * 定向推广绑定事件JS
 * @module self_direction
 * @file js/app/self_direction/direction.js
 * @requires js/app/self_direction/direction.js
 * @namespace GJ.app.self_direction
 * @author chenchaofei@ganji.com
 */


GJ.add(
'js/app/self_direction/direction.js',
['jquery', 'log_tracker'],
function() {

    GJ.app = GJ.app || {};
    GJ.app.selfDirection = GJ.app.selfDirection || {};
    GJ.app.selfDirection.bind = function(config){
        var conf = {
            postClass : 'js_self_direction_post',
            attrHref : '_href',
            attrSign : 'sign'
        };
        conf = GJ.mix(conf, config || {}, true);

        //为click.ganji.com添加点击时的x，y坐标

        $(config.$el).on('click','a',function(e){
            var baseOffset = config.$el.offset();
            var href = $(this).attr('href');
            if(href.indexOf('click.ganji.com') > -1) {
                var x = parseInt(e.pageX - baseOffset.left, 10);
                var y = parseInt(e.pageY - baseOffset.top, 10);

                href = href.replace(/&x=.*/, '');
                href += '&x=' + x + '&y=' + y;
                $(this).attr('href', href);
            }
        });

        $('.'+conf.postClass+', a[sign]').filter(':not([_sd])').bind('click', function(){
//            var _href = $(this).attr(conf.attrHref)||false
//            ,   _sign = $(this).attr(conf.attrSign)
//            ,   _time = new Date().getTime()
//            ;
//            if(!_href) {
//                _href = $(this).attr('href');
//                $(this).attr(conf.attrHref, _href);
//            }
//            $(this).attr('href', _href+'#'+_time+'|'+_sign);
            if (!GJ.getCookie('GanjiUserInfo')) {
                GJ.setCookie('webimVisitorNeedComet', '1', 3600 * 24 * 14);
            }
        }).attr('_sd', '1');

        if(GJ.LogTracker.gjch != '' && GJ.LogTracker.gjch != '_' && GJ.LogTracker.gjch != '-') {
        	GJ.LogTracker.bindAllTrackEvent();
    	}
    };

    GJ.app.selfDirection.render = function(config){
        var paramsList = {};
        var $rendBox = $('.js-direction-render-box');
        $rendBox.each(function(){
            if($(this).data('dxing')) {
                return true;
            }
            var boxid = $(this).data('boxid');
            var params = $(this).data('params');
            $(this).data('dxing', true);
            paramsList['params['+boxid+']'] = params;
        });
        if($.isEmptyObject(paramsList)){
            return true;
        }
        $.post('/ajax.php?dir=self_direction&module=render', paramsList, function(res){
            for(var id in res) {
                $rendBox.filter('[data-boxid='+id+']').html(res[id]).show();
            }
            GJ.app.selfDirection.bind();

            if ($rendBox.find('.js-lazy-load').size()) {
                GJ.use('js/util/lazyload/jquery.lazyload.1.7.js', function () {
                    $rendBox.find('.js-lazy-load').each(function () {
                        $(this).lazyload();
                    });
                });
            }
        },'json');
    };

    GJ.app.selfDirection.send = function(config){
        var conf = {
            after : 10,		//10毫秒
            befor : 30000   //30秒
        };
        conf = GJ.mix(conf, config || {}, true);

        var hash = window.location.hash
        ,   result = hash.substring(hash.lastIndexOf('#')+1)
        ,   beginTime = new Date().getTime()
        ,   isSend = false
        ,   isRealView = false
        ,   sendDirection = function(){
                if(isSend || !isRealView){
                    return true;
                }
                if(new Date().getTime()-beginTime>conf.after) {
                    isSend = true;
                    $.getJSON('http://www.ganji.com/ajax.php?dir=self_direction&module=view_post&callback=?', {s:result}, function(res){
                    });
                }
            }
        ;
    	GJ.LogTracker.trackEvent('/self_direction/clickJs/toShowFalse@atype=show@s='+result);

        if(!result) {
//            GJ.log('direction hash is empty');
            return false;
        }
        var arr = result.split('|');
        if(arr.length != 2) {
//            GJ.log('direction hash length fail');
            return false;
        }

        if(beginTime - arr[0] > conf.befor) {
//            GJ.log('direction time out');
            return false;
        }

        if(typeof(arr[1]) == "undefined" || arr[1].length < 10) {
//        	GJ.log('sign is undefined');
            return false;
        }

        $('body').mousemove(function(){
            isRealView=true;
            sendDirection();
        });

        $(window).on('scrollEvent', function() {
            isRealView = true;
            sendDirection();
        });
        window.onunload = function() {
            if(!isSend) {
                $.getJSON('http://www.ganji.com/ajax.php?dir=self_direction&module=log');
            }
        };

        setTimeout(function(){sendDirection();}, conf.after);
    };

});
